package ltd.hyangyang.rpc.common.utils;

import ltd.hyangyang.rpc.common.exception.RpcException;

import java.net.InetSocketAddress;

public class AddrUtils {
    public static InetSocketAddress getInetSocketAddress(String addr){
        String ip = getIp(addr);
        Integer port = getPort(addr);
        if (ip!=null&&port!=null){
            return new InetSocketAddress(ip,port);
        }
        throw new NullPointerException();
    }

    public static String getIp(String addr){
        String[] addrs = addr.split(":");
        if (addrs.length!=2){
            throw new RpcException("网络地址的格式不正确，正确的格式应该是ip:prot");
        }
        return addrs[0];
    }

    public static Integer getPort(String addr){
        String[] addrs = addr.split(":");
        if (addrs.length!=2){
            throw new RpcException("网络地址的格式不正确，正确的格式应该是ip:prot");
        }
        return Integer.parseInt(addrs[1]);
    }
}
